package fr.tocchisu.grepolis.requests;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import fr.tocchisu.grepolis.model.SendUnit;
import fr.tocchisu.grepolis.model.Town;

public class NormalAttackRequest extends AbstractHTTPRequest {

	private Town town;
	private List<SendUnit> attackUnits;
	private int targetedTown;

	public NormalAttackRequest(Town town, int targetedTown, SendUnit... attackUnits) {
		this.town = town;
		this.attackUnits = Arrays.asList(attackUnits);
		this.targetedTown = targetedTown;
	}

	@Override
	protected String getURL() {
		return "town_info?action=send_units&town_id=" + town.getId() + "&h=" + H;
	}

	@Override
	protected String getPostDatas() {
		StringBuilder result = new StringBuilder("{");
		List<String> attackUnitsParams = new ArrayList<String>(attackUnits.size());
		for (SendUnit attackUnit : attackUnits) {
			String unitName = attackUnit.getUnit().name().toLowerCase();
			String unitNumber = Integer.toString(attackUnit.getNumber());
			if (Integer.parseInt(unitNumber) > 0) {
				attackUnitsParams.add("\"" + unitName + "\":" + unitNumber);
			}

		}
		result.append(StringUtils.join(attackUnitsParams, ","));
		result.append(",\"id\":" + targetedTown);
		result.append(",\"type\":\"attack\",\"attacking_strategy\":\"" + getAttackType() + "\",\"town_id\":\"" + town.getId()
				+ "\",\"nlreq_id\":22468706");
		result.append("}");
		// json
		// {"sword":9,"slinger":9,"archer":9,"hoplite":9,"rider":9,"chariot":9,"catapult":9,"zyklop":9,"godsent":9,"big_transporter":9,"bireme":9,"attack_ship":9,"demolition_ship":9,"small_transporter":9,"trireme":9,"colonize_ship":9,"sea_monster":9,"id":33696,"type":"attack","attacking_strategy":"regular","town_id":"34278","nlreq_id":22468706}
		// json=%7B%22slinger%22%3A100%2C%22big_transporter%22%3A20%2C%22id%22%3A34336%2C%22type%22%3A%22attack%22%2C%22attacking_strategy%22%3A%22regular%22%2C%22town_id%22%3A%2240612%22%2C%22nlreq_id%22%3A22718234%7D
		// json=%7B%22slinger%22%3A100%2C%22big_transporter%22%3A20%2C%22id%22%3A33696%2C%22type%22%3A%22attack%22%2C%22attacking_strategy%22%3A%22regular%22%2C%22town_id%22%3A%2240612%22%2C%22nlreq_id%22%3A22468706%7D
		try {
			return "json=" + URLEncoder.encode(result.toString(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			System.out.println("Bad encoding");
			System.exit(0);
			return null;
		}
	}

	/**
	 * @return
	 */
	protected String getAttackType() {
		return "regular";
	}

}
